package com.feilong.edgeAI.service;

import static com.feilong.edgeAI.speech.TTSHelper.LANGUAGE_EN_TYPE;
import static com.feilong.edgeAI.speech.TTSHelper.TEXT_TYPE;
import static com.feilong.edgeAI.speech.TTSHelper.TIPS_TYPE;
import static com.feilong.edgeAI.ui.HomeActivity.AI_MODE;
import static com.feilong.edgeAI.ui.HomeActivity.AI_TOGGLE;
import static com.feilong.edgeAI.ui.HomeActivity.ONLINE_AI;
import static com.feilong.edgeAI.vm.SettingViewModel.TTS_SCALE;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import androidx.annotation.RequiresApi;

import com.aiibt.common.util.Constant;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feilong.edgeAI.R;
import com.feilong.edgeAI.autosendwechatmsg.WeChatTextWrapper;
import com.feilong.edgeAI.autosendwechatmsg.WechatUtils;
import com.feilong.edgeAI.buletooth.ECBLEConnectionStateChangeCallback;
import com.feilong.edgeAI.buletooth.ECBluetoothDeviceFoundCallback;
import com.feilong.edgeAI.model.AINetRespone;
import com.feilong.edgeAI.model.AIRespone;
import com.feilong.edgeAI.model.AIUICleanMsg;
import com.feilong.edgeAI.model.AIUIMsg;
import com.feilong.edgeAI.model.AddWarnMsg;
import com.feilong.edgeAI.model.AskFeilong;
import com.feilong.edgeAI.model.BaseResult;
import com.feilong.edgeAI.model.BlueConnect;
import com.feilong.edgeAI.model.CloseVoice;
import com.feilong.edgeAI.model.DeleteWarnMsg;
import com.feilong.edgeAI.model.MaxMsg;
import com.feilong.edgeAI.model.PPMessage;
import com.feilong.edgeAI.model.PlayTTs;
import com.feilong.edgeAI.model.QueryWarnMsg;
import com.feilong.edgeAI.model.RequestXXZLastTest;
import com.feilong.edgeAI.model.ResetAwakeWords;
import com.feilong.edgeAI.model.BlueToochEnable;
import com.feilong.edgeAI.model.BlueToothMsg;
import com.feilong.edgeAI.model.Commands;
import com.feilong.edgeAI.model.CopyFile;
import com.feilong.edgeAI.model.CurrentUI;
import com.feilong.edgeAI.model.FloatViewState;
import com.feilong.edgeAI.model.GlobalEvent;
import com.feilong.edgeAI.model.IflytekError;
import com.feilong.edgeAI.model.LocationBase;
import com.feilong.edgeAI.model.NoticeMsg;
import com.feilong.edgeAI.model.NotificationText;
import com.feilong.edgeAI.model.Setaimode;
import com.feilong.edgeAI.model.ShowDownLoadDialog;
import com.feilong.edgeAI.model.StarOnLineMsg;
import com.feilong.edgeAI.model.StartAIUI;
import com.feilong.edgeAI.model.StartAskMsg;
import com.feilong.edgeAI.model.StartOnceMsg;
import com.feilong.edgeAI.model.StartTextAIUI;
import com.feilong.edgeAI.model.StartVoice;
import com.feilong.edgeAI.model.StopAIUI;
import com.feilong.edgeAI.model.TakeVideo;
import com.feilong.edgeAI.model.TcpUpdateFeiLong;
import com.feilong.edgeAI.model.TestUpdate;
import com.feilong.edgeAI.model.TestXxzUpdate;
import com.feilong.edgeAI.model.ToastMsg;
import com.feilong.edgeAI.model.ToggleMsg;
import com.feilong.edgeAI.model.TtsMsg;
import com.feilong.edgeAI.model.UserStopWakeUp;
import com.feilong.edgeAI.model.WechatHome;
import com.feilong.edgeAI.model.WechatHomeFinish;
import com.feilong.edgeAI.model.WeixinMsg;
import com.feilong.edgeAI.model.FeilongRespone;
import com.feilong.edgeAI.receiver.BootBroadcastReceiver;
import com.feilong.edgeAI.receiver.LanguageChangeReceiver;
import com.feilong.edgeAI.remind.alarm.AlarmClockHelper;
import com.feilong.edgeAI.remind.room.bean.RemindBean;
import com.feilong.edgeAI.remind.room.db.RemindDatabase;
import com.feilong.edgeAI.request.RetrofitUtil;
import com.feilong.edgeAI.speech.TransHelper;
import com.feilong.edgeAI.ui.DeviceListActivity;
import com.feilong.edgeAI.ui.ECBLE;
import com.feilong.edgeAI.ui.SettingActivity;
import com.feilong.edgeAI.utils.AlertVoiceManager;
import com.feilong.edgeAI.utils.AppConstant;
import com.feilong.edgeAI.utils.ChineseNumberConverter;
import com.feilong.edgeAI.utils.EdgeManager;
import com.feilong.edgeAI.utils.FileUtil;
import com.feilong.edgeAI.utils.NetworkUtil;
import com.feilong.edgeAI.utils.TextUtil;
import com.feilong.edgeAI.view.AlertAlarmView;
import com.feilong.edgeAI.view.GlobalFloatingView;
import com.feilong.edgeAI.vm.MainViewModel;
import com.feilong.mscv5plus.MessageClient;
import com.feilong.edgeAI.speech.EdHelper;
import com.feilong.edgeAI.speech.IvwHelper;
import com.feilong.edgeAI.speech.TTSHelper;
import com.feilong.edgeAI.speech.online.AsrHelper;
import com.feilong.edgeAI.speech.util.PlayerUtils;
import com.feilong.edgeAI.speech.AbilityInit;
import com.feilong.edgeAI.utils.AppUtils;
import com.feilong.edgeAI.utils.MusicPlayer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import pub.devrel.easypermissions.EasyPermissions;

/**
 * 业务处理服务
 */
public class FeiLongService extends Service implements GlobalFloatingView.OnClickFloatListener {

    public static final int ONLINE_AI = 1;
    public static final int OFFLINE_AI = 2;

    private boolean isToggle = false;

    public FeiLongService() {
    }

    private static final String TAG = "FeiLongService";
    private static final String CHANNEL_ID = "ForegroundServiceChannel";
    private static final int NOTIFICATION_ID = 101;
    //    private TtsUtils ttsHelper;
    private AudioManager audioManager;
    private int maxVol;
    private PlayerUtils playerUtils;

    private TTSHelper ttsHelpers;

    private CallEndReceiver callEndReceiver;
    private AewmeService aewmeService;
    private String currentRequest;
    private long lastRequestTime;
    private long closeVoiceLayoutTime;
    private IvwHelper ivwHelper;
    private AsrHelper asrHelper;
    private EdHelper edHelper;
    private TransHelper transHelper;
    public static String currentTTS;
    private String currenString = "";

    private boolean interactionMode;
    private BootBroadcastReceiver bootBroadcast;
    private AlertVoiceManager alertVoiceManager;
    private BLEStateReceiver bleStateReceiver;
    private LanguageChangeReceiver langChangeReceiver;

    private GlobalFloatingView floatingView;//全局浮窗
    private AlertAlarmView alertAlarmView;
    private RetrofitUtil retrofitUtil;
    private boolean onlineMode;
    private String Flow = "0";

    private String Mode = "1";
    private String Session = "";

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground();
        Log.e(TAG, "onStartCommand: >>>>>" + alertVoiceManager);
        alertVoiceManager = new AlertVoiceManager(this);
        requestLocation();
        registeNetWork();
        aewmeService = AewmeService.getInstance();//初始化无障碍服务
        aewmeService.init(this);
        if (!AppUtils.checkAccess(this)) {
            sendBroadcast(new Intent("com.feilong.edgeAI.action.FEILONG_OPEN_ACCESSIBILITY"));
        }
        // TODO: Handle your server logic here
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        edHelper = new EdHelper();
        transHelper = new TransHelper();
        ivwHelper = new IvwHelper(this, edHelper);
        asrHelper = new AsrHelper(this);
        TcpClient.startClient();
        EdgeManager.getInstance().setContext(this);//手机系统功能
        callEndReceiver = new CallEndReceiver();
        IntentFilter filter1 = new IntentFilter("android.intent.action.PHONE_STATE");
        filter1.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(callEndReceiver, filter1);
        bootBroadcast = new BootBroadcastReceiver();
        IntentFilter filter2 = new IntentFilter();
        filter2.addAction(Intent.ACTION_BOOT_COMPLETED);
        registerReceiver(bootBroadcast, filter2);
        IntentFilter blueFilter = new IntentFilter();
        // 监视蓝牙关闭和打开的状态
        blueFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        bleStateReceiver = new BLEStateReceiver();
        registerReceiver(bleStateReceiver, blueFilter);
        langChangeReceiver = new LanguageChangeReceiver();
        IntentFilter langChangeFilter = new IntentFilter();
        langChangeFilter.addAction("android.intent.action.LOCALE_CHANGED");
        registerReceiver(langChangeReceiver, langChangeFilter);
        playerUtils = new PlayerUtils();
        playerUtils.initPlayer(this);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        maxVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        floatingView = new GlobalFloatingView(getApplicationContext());
        alertAlarmView = new AlertAlarmView(getApplicationContext());
        floatingView.setOnClickFloatListener(this);
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        //2.注册电话的监听
        tm.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        if (AppUtils.getIflyFileExist()) {
            initAbility();
        }
        checkScreen();
        String deviceMac = SPUtils.getInstance().getString(ECBLE.DEVICE_MAC);
        permissionsBlueToochInit(!TextUtils.isEmpty(deviceMac));
        retrofitUtil = new RetrofitUtil();
        return START_STICKY;
    }

    /**
     * 初始化讯飞离线能力
     */
    public void initAbility() {
        Log.d(TAG, "initAbility: ====");
        ttsHelpers = new TTSHelper();
        AbilityInit ability = new AbilityInit();
        ability.setOnAuthSuccessListener(new AbilityInit.OnAuthSuccessListener() {
            @Override
            public void onAuthSuccess() {
                handler.removeMessages(RESTART_VOICE);
                initVoice();
            }

            @Override
            public void onAuthFailure() {
            }
        });
        ability.init(this);

    }
//

    /**
     * 初始化和启动讯飞离线唤醒
     */
    private void initVoice() {
        Log.d(TAG, "initVoice: ");
        edHelper.init();
        transHelper.init();
        ivwHelper.startIvw();
        ivwHelper.startRecord();
        ivwHelper.setIvwHelperListener(new IvwHelper.IvwHelperListener() {
            @Override
            public void onWakeup(boolean online) {
//                if (OFFLINE_AI != SPUtils.getInstance().getInt(AI_MODE)) {
//                    SPUtils.getInstance().put(AI_MODE, OFFLINE_AI);
//                    EventBus.getDefault().post(new Setaimode("2"));
//                    EventBus.getDefault().post(new Commands("机器人服务助理"));
//
//                } else {
//                    EventBus.getDefault().post(new ToggleMsg());
//                }
                int t = SPUtils.getInstance().getInt(AI_TOGGLE, 1);
                if (!online) {
                    SPUtils.getInstance().put(AI_MODE, OFFLINE_AI);
                    SPUtils.getInstance().put(AI_TOGGLE, 1);
                    EventBus.getDefault().post(new Setaimode("2"));
                    if (t == 0) {
                        isToggle = true;
                        EventBus.getDefault().post(new Commands("机器人服务助理"));
                    } else {
                        isToggle = false;
                    }
                    commonOnWakeup(TTSHelper.AWAKE_TYPE);
                } else {
                    SPUtils.getInstance().put(AI_TOGGLE, 0);
                    EventBus.getDefault().post(new Setaimode("1"));
                    EventBus.getDefault().post(new ToggleMsg());
//                    awakeModel();
//                    handler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            floatingView.recognitionModel();
//                        }
//                    }, 3000);
//                    EventBus.getDefault().post(new AIUIMsg("0"));
                    if (t == 0) {
                        EventBus.getDefault().post(new StarOnLineMsg("0"));
                    } else {
                        EventBus.getDefault().post(new StarOnLineMsg("1"));
                    }

                }
//                commonOnWakeup(TTSHelper.AWAKE_TYPE);
            }

            @Override
            public void onVolume(int volume, boolean recognition) {
                Message message = Message.obtain();
                message.arg1 = volume;
                message.what = SET_VOLUME;
                handler.sendMessage(message);
            }
        });

        edHelper.setEdListener(new EdHelper.EdListener() {
            @Override
            public void onEdRecognting(String result) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        floatingView.setRecognitionText(result);
                    }
                });

            }

            @Override
            public void onEdResult(String result) {
                Log.e(TAG, "onEdResult: " + result);
                recognitionResult(result);
            }

            @Override
            public void onError() {
                startSpeechRecognition();
                handler.sendEmptyMessage(RECOGNITIONMODEL);
            }

            @Override
            public void onStart() {
                handler.sendEmptyMessage(RECOGNITIONMODEL);
            }
        });

        ttsHelpers.setOnTTSListener(new TTSHelper.OnTTSListener() {
            @Override
            public void onTTSFinish(int type) {
                ttsFinish(type);
            }

            @Override
            public void onError() {
                Log.d(TAG, "onTTSFinish onError: ivwHelper.startIvw()");
            }
        });
        asrHelper.setAsrHelperListener(new AsrHelper.AsrHelperListener() {
            @Override
            public void onAsrFinish(String result) {
                Log.d(TAG, "onAsrFinish: " + result);
                recognitionResult(result);
            }

            @Override
            public void onEndOfSpeech() {
                Log.d(TAG, "asrHelper onEndOfSpeech: ivwHelper.startIvw()");
            }
        });
        ivwHelper.setOnIvwErrorListener(new IvwHelper.OnIvwErrorListener() {
            @Override
            public void onIvwError() {
//                handler.sendEmptyMessageDelayed(IVW_RESTART,5000);
            }
        });
        transHelper.setOnTranslateResultListener(new TransHelper.onTranslateResultListener() {
            @Override
            public void onTranslate(String original, String result, String type) {
                Log.d(TAG, "onTranslate:result= " + result + "  type=" + type);
                if (TransHelper.ENCN.equals(type)) {
                    sendToFeiLong(original, result, "EN");
                } else if (TransHelper.CNEN.equals(type)) {
//                    sendToFeiLong(result,"CN");
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            floatingView.setAnswerViewText(result);
                        }
                    });
                    ttsHelpers.startTTS(result, TTSHelper.TEXT_TYPE, LANGUAGE_EN_TYPE);
                }
            }

            @Override
            public void onError() {

            }
        });
    }

    private void commonOnWakeup(int type) {
        askContent = "";
        boolean exaAlive = AppUtils.checkAlive(FeiLongService.this, AewmeService.EXAGEAR_PKG);
        Log.d(TAG, "onWakeup: " + exaAlive);
        if (null != feilongRespone) {
            feilongRespone.setIntent("");
        }
        Log.d(TAG, "onWakeup: checkAccess=" + AppUtils.checkAccess(FeiLongService.this));
        if (!AppUtils.checkAccess(FeiLongService.this)) {
            Log.d(TAG, "onWakeup: FEILONG_OPEN_ACCESSIBILITY");
            sendBroadcast(new Intent("com.feilong.edgeAI.action.FEILONG_CLOSE_ACCESSIBILITY"));
            sendBroadcast(new Intent("com.feilong.edgeAI.action.FEILONG_OPEN_ACCESSIBILITY"));//打开无障碍
        }
        checkScreen();//MOBILE_NETWORK

        handler.post(new Runnable() {
            @Override
            public void run() {
                floatingView.setRecognitionText("");
            }
        });
        Log.d(TAG, "onWakeup: TTSHelper.eventType=" + TTSHelper.eventType);
//                if (TTSHelper.eventType != 2) {
        if (!isToggle) {
            ttsHelpers.setInterrupted(true);
            ttsHelpers.endTTS();
//                }
            Log.d(TAG, "onWakeup: stopSpeechRecognition");
            stopSpeechRecognition();
            playerUtils.play();
            musicPlayer.stop();
            ttsHelpers.startTTS("我在", type);
//            ttsHelpers.startTTS("好的，在线机器人聊天助理为您服务！\n" +
//                    "            主人，您请说：", type);

        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                floatingView.setRecognitionText(getResources().getString(R.string.listening));
            }
        });
    }

    private void commonOnFirstWakeup(int type) {
        askContent = "";
        boolean exaAlive = AppUtils.checkAlive(FeiLongService.this, AewmeService.EXAGEAR_PKG);
        Log.d(TAG, "onWakeup: " + exaAlive);
        if (null != feilongRespone) {
            feilongRespone.setIntent("");
        }
        Log.d(TAG, "onWakeup: checkAccess=" + AppUtils.checkAccess(FeiLongService.this));
        if (!AppUtils.checkAccess(FeiLongService.this)) {
            Log.d(TAG, "onWakeup: FEILONG_OPEN_ACCESSIBILITY");
            sendBroadcast(new Intent("com.feilong.edgeAI.action.FEILONG_CLOSE_ACCESSIBILITY"));
            sendBroadcast(new Intent("com.feilong.edgeAI.action.FEILONG_OPEN_ACCESSIBILITY"));//打开无障碍
        }
        checkScreen();//MOBILE_NETWORK

        handler.post(new Runnable() {
            @Override
            public void run() {
                floatingView.setRecognitionText("");
            }
        });
        Log.d(TAG, "onWakeup: TTSHelper.eventType=" + TTSHelper.eventType);
//                if (TTSHelper.eventType != 2) {
        if (!isToggle) {
            ttsHelpers.setInterrupted(true);
            ttsHelpers.endTTS();
//                }
            Log.d(TAG, "onWakeup: stopSpeechRecognition");
            stopSpeechRecognition();
            playerUtils.play();
            musicPlayer.stop();
            ttsHelpers.startTTS("好的，在线机器人聊天助理为您服务", type);
//            ttsHelpers.startTTS("好的，在线机器人聊天助理为您服务！\n" +
//                    "            主人，您请说：", type);

        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                floatingView.setRecognitionText(getResources().getString(R.string.listening));
            }
        });
    }

    /**
     * 开始录音
     */
    private void startSpeechRecognition() {
        if (null != cancelable) {
            cancelable.cancel();
        }
        if (null != ttsHelpers && !ttsHelpers.isEnd()) {
            ttsHelpers.stop();
        }
        int language = SPUtils.getInstance().getInt(SettingActivity.SELECT_LANGUAGE, 0);
        if (language == 1) {
            asrHelper.start();//粤语（在线）
        } else {
            ivwHelper.startEd();//普通话（离线）
        }
    }

    /**
     * 停止录音
     */
    private void stopSpeechRecognition() {
        int language = SPUtils.getInstance().getInt(SettingActivity.SELECT_LANGUAGE, 0);
        if (language == 1) {
            asrHelper.stop();
        } else {
            if (ivwHelper.getEDState()) {
                ivwHelper.stopEd();
            }
        }
    }

    private String askContent;

    /**
     * 对识别结果的文本处理
     *
     * @param result
     */
    private void recognitionResult(String result) {

//
        count = 0;
//        拦截词（命令词）设计
//        A.添加提醒命令词
//          提醒我              //提醒对象：用户
//          提醒机器人       //提醒对象：物联网模组（在理解引擎中）
//          帮我                 //提醒对象：飞龙大师其他模块
//        B.查询提醒命令词
//          有哪些提醒
//        C.删除提醒命令词
//          删除提醒
//        D.开关提醒
//          开启/关闭提醒
        if (!result.isEmpty() && result.length() > 0) {
            if (result.contains("提醒我")) {
                addWarn(result);
                return;
            } else if (result.contains("提醒机器人")) {
//                addWarn(result);
            } else if (result.contains("帮我")) {
//                addWarn(result);
            } else if (result.contains("有哪些提醒")) {
//                queryWarn();
            } else if (result.contains("删除提醒")) {
//                deleteWarn();
            } else if (result.contains("开启提醒")) {

            } else if (result.contains("关闭提醒")) {

            } else if (result.contains("修改提醒")) {

            }
        }

        if (1 != SPUtils.getInstance().getInt(AI_TOGGLE)) {
            EventBus.getDefault().post(new MaxMsg(result));
            return;
        }
//        if (!result.isEmpty() && result.length() > 0 && result.contains("小飞小飞")) {
//            return;
//        }
        if (!result.isEmpty() && result.length() > 0) {
            if (result.contains("进入购物模式")) {
                Session = String.valueOf(System.currentTimeMillis()) + "fangnao";
                Flow = "0";
                onlineMode = true;
//                ttsHelpers.startTTS("好的，已进入购物模式", TTSHelper.TEXT_TYPE);
            } else if (result.contains("退出购物模式")) {
                Session = "";
                Flow = "0";
                onlineMode = false;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        floatingView.cleanVoiceData();
                    }
                });

                ttsHelpers.startTTS("好的，已退出购物模式", TTSHelper.TEXT_TYPE);
            } else if (result.contains("进入旅游模式")) {
                onlineMode = true;
                ttsHelpers.startTTS("好的，已进入旅游模式", TTSHelper.TEXT_TYPE);
            } else if (result.contains("退出旅游模式")) {
                onlineMode = false;
                ttsHelpers.startTTS("好的，已退出旅游模式", TTSHelper.TEXT_TYPE);
            } else if (result.contains("进入周边推荐模式")) {
                onlineMode = true;
                ttsHelpers.startTTS("好的，已进入周边推荐模式", TTSHelper.TEXT_TYPE);
            } else if (result.contains("退出周边推荐模式")) {
                onlineMode = false;
                ttsHelpers.startTTS("好的，已退出周边推荐模式", TTSHelper.TEXT_TYPE);
            } else if (result.contains("进入音乐模式")) {
                onlineMode = true;
                ttsHelpers.startTTS("好的，已进入音乐模式", TTSHelper.TEXT_TYPE);
            } else if (result.contains("退出音乐模式")) {
                onlineMode = false;
                ttsHelpers.startTTS("好的，退出音乐模式", TTSHelper.TEXT_TYPE);
            }

            if (onlineMode) {
                getNetTalk(Flow, result, Mode);
                return;
            }
        }

        if (result.equals("重启语音助手主程序")) {
            AppUtils.reStartSelf(FeiLongService.this);
            Log.d(TAG, "recognitionResult: stopSpeechRecognition");
            stopSpeechRecognition();
            handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
        }
       /* if (result.contains("发消息给")) {
            PPMessage message = new PPMessage();
            message.setType(0);
            message.setMessage("你在哪里");
            EventBus.getDefault().post(message);
            return;
        }
        if (result.contains("打语音电话给")) {
            PPMessage message = new PPMessage();
            message.setType(1);
            EventBus.getDefault().post(message);
            return;
        }*/
        /*if (result.contains("打视频电话给")) {
            PPMessage message = new PPMessage();
            message.setType(2);
            EventBus.getDefault().post(message);
            return;
        }*/
        if (result.equals("升级语音助手")) {
            handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
            EventBus.getDefault().post(new TestUpdate());
            stopSpeechRecognition();
            return;
        }
        if (result.contains("升级理解")) {
            EventBus.getDefault().post(new RequestXXZLastTest());
//            updateFeilong();
            stopSpeechRecognition();
            handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
            return;
        }
        if (result.contains("[{")) return;
        String check = result.replaceAll(" ", "");

        askContent = result;
        handler.post(new Runnable() {
            @Override
            public void run() {
                floatingView.setAskViewText(askContent);
            }
        });
        if (TextUtils.isEmpty(check)) {
            handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
//            stopSpeechRecognition();
//            startSpeechRecognition();
        } else {
            handler.sendEmptyMessage(AWAKEMODEL);
            currenString = result;
            if (TextUtil.containsChinese(result) || TextUtil.isNumeric(result)) {
                enType = false;
                sendToFeiLong(result);
                currentRequest = result;
                lastRequestTime = System.currentTimeMillis();
            } else {
                enType = true;
                transHelper.translate(TransHelper.ENCN, result);
            }
        }
        //把询问过的语句保存
        FileUtil.appendText(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "reclog.txt", result);
    }

    public static final String WAKEUP_STATE = "wakeup_state";

    private void stopVoice() {
        SPUtils.getInstance().put(WAKEUP_STATE, false);
        if (null != ivwHelper) {
            ivwHelper.stopIvw();
            ttsHelpers.setInterrupted(true);
            ttsHelpers.endTTS();
            musicPlayer.stop();
        }
    }

    private String undoString;

    /**
     * 发送intent
     *
     * @param intent
     */
    private void sendToFeiLongByIntent(String intent) {
        resendTime = 0;
        FeilongRespone request = new FeilongRespone("0", intent);
//        handler.removeMessages(TCP_CHECK);
        TcpClient.sendTcpMessage(new Gson().toJson(request));
//        Log.d(TAG, "sendToFeiLonginit: =" + new Gson().toJson(request));
    }

    private void sendToFeiLong(String result) {
        sendToFeiLong("", result, "CN");
    }

    private void sendToFeiLongByUI(String result) {
        sendToFeiLong("", result, "CN", "UI");
    }

    /**
     * @param result
     * @param language CN/EN
     */
    private void sendToFeiLong(String original, String result, String language, String from) {
        resendTime = 0;
        FeilongRespone request = new FeilongRespone("0", result, "rec");
        request.setLanguage(language);
        request.setFrom(from);
        if (!TextUtils.isEmpty(original)) {
            request.setEtext(original);
        }
        sendToTcp(request);
    }

    private void sendToFeiLong(String original, String result, String language) {
        resendTime = 0;
        FeilongRespone request = new FeilongRespone("0", result, "rec");
        request.setLanguage(language);
        if (!TextUtils.isEmpty(original)) {
            request.setEtext(original);
        }
        sendToTcp(request);
    }

    /**
     * 通过tcp发送给离线理解
     *
     * @param
     */
    private void sendToTcp(FeilongRespone request) {
        if (!NetworkUtil.isNetworkAvailable(this)) {
            request.setNet("fail");
        }
        request.setMode(SPUtils.getInstance().getInt(AI_MODE, ONLINE_AI) + "");//告诉理解引擎mode=1是在线模式，mode=2是离线模式
        String content = new Gson().toJson(request);
        resendTime = 0;
        undoString = content;
//        handler.removeMessages(TCP_CHECK);
        TcpClient.sendTcpMessage(content);
        handler.sendEmptyMessageDelayed(LOCAL_FEILONG_NOT_RESPONE, 3000);

        Log.d(TAG, "sendToFeiLong: =" + content);
        handler.sendEmptyMessageDelayed(CHECK_EXAGEAR, 400);
    }

    /**
     * 听书功能，听完一章节后执行这个方法，会获取到下一章
     */
    private void listenBook() {
        FeilongRespone request = new FeilongRespone("0", "tts_end");
        TcpClient.sendTcpMessage(new Gson().toJson(request));
        Log.d(TAG, "listenBook: " + new Gson().toJson(request));
    }

    /**
     * tts播放完成
     *
     * @param type
     */
    private void ttsFinish(int type) {
        handler.removeMessages(CLOSE_VOICE_LAYOUT);
        if ("continue".equals(currentMode)) {
            startSpeechRecognition();
            handler.sendEmptyMessage(RECOGNITIONMODEL);
        } else {
            switch (type) {
                case TTSHelper.AWAKE_TYPE:
                    startSpeechRecognition();
                    handler.sendEmptyMessage(RECOGNITIONMODEL);
                    break;
                case TTSHelper.CONTINIE_TYPE:
                    startSpeechRecognition();
                    handler.sendEmptyMessage(RECOGNITIONMODEL);
                    break;
                case TTSHelper.TEXT_TYPE:
                    if (interactionMode) {
                        startSpeechRecognition();
                        handler.sendEmptyMessage(RECOGNITIONMODEL);
                    } else {
                        Log.d(TAG, "ttsFinish: stopSpeechRecognition");
                        stopSpeechRecognition();
                    }
                    break;
                case TTSHelper.BOOK_TYPE:
                    listenBook();
                    break;
                case TTSHelper.AWAKE_ONE_TYPE:
                    handler.sendEmptyMessage(AWAKEMODEL);
                    break;
                case TTSHelper.TIPS_TYPE:
                    showOnlieResult();
                    return;
            }
        }
        Log.d(TAG, "ttsFinish:type= " + type);
        if (interactionMode) {
            Log.d(TAG, "onTTSFinish: 交互模式");
            closeVoiceLayoutTime = EdHelper.VADRESPONSETIME;
        } else {
            Log.d(TAG, "onTTSFinish: 唤醒模式");
            closeVoiceLayoutTime = 50000;
        }
        Log.d(TAG, "onTTSFinish: CLOSE_VOICE_LAYOUT=" + closeVoiceLayoutTime + "  TEXT_TYPE= " + type + " interactionMode=" + interactionMode);

        Log.d(TAG, "@@@ttsFinish: last");
        handler.sendEmptyMessageDelayed(CLOSE_VOICE_LAYOUT, closeVoiceLayoutTime);
        EventBus.getDefault().post(new StartAIUI());
    }


    private static final int STARTLISTENING = 0;
    private static final int TCP_CHECK = 1;//检查tcp
    private static final int IAT_RESULT = 2;
    private static final int IAT_RESULT_RESET = 3;
    private static final int REQUEST_BLUETOOCH = 4;
    private static final int IVW_RESTART = 5;
    private static final int CONNECT_FEILONG = 6;//重连tcp
    private static final int LUANCH_WEIXIN = 7;
    private static final int RECOGNITIONMODEL = 9;
    private static final int AWAKEMODEL = 10;
    private static final int SET_VOLUME = 11;
    private static final int CLOSE_VOICE_LAYOUT = 12;
    private static final int LOCAL_FEILONG_NOT_RESPONE = 13;
    private static final int CHECK_EXAGEAR = 14;
    private static final int RESTART_VOICE = 15;
    private static final int SEND_BLUETOOTHMSG = 16;
    private static final int SEND_UNSEND_BLUETOOCH = 17;
    private String tag;
    private int resendTime;
    private int blueConnectTime;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SEND_UNSEND_BLUETOOCH:
                    handler.removeMessages(SEND_UNSEND_BLUETOOCH);
                    if (resendTime > 2) {//重发3次没有成功就重新连接蓝牙
                        Log.d(TAG, "handleMessage: reConnectTime=" + blueConnectTime);
                        if (blueConnectTime < 2) {
                            reConnectBlueTooch();
                        }
                        resendTime = 0;
                    } else {
                        setSendUnsendBluetooch();
                        resendTime++;
                    }

                    break;
                case CHECK_EXAGEAR:
//                    ttsHelpers.startTTS("理解引擎连接失败", TEXT_TYPE);
//                    floatingView.setAnswerViewText("理解引擎连接失败");
//                    hasOpenExagear = false;
//                    TcpClient.startClient();
                    break;
                case TCP_CHECK:
                    sendToFeiLongByIntent("none");//发送心跳数据
                    handler.sendEmptyMessageDelayed(TCP_CHECK, 1000);
                    break;
                case SEND_BLUETOOTHMSG:
                    handler.removeMessages(SEND_BLUETOOTHMSG);
                    BlueToothMsg blueToothMsg = (BlueToothMsg) msg.obj;
                    handleBlueToothMsg(blueToothMsg);
                    break;
                case CONNECT_FEILONG:
                    handler.removeMessages(CONNECT_FEILONG);
                    TcpClient.startClient();
                    break;
                case IVW_RESTART:
                    handler.removeMessages(IVW_RESTART);
                    break;
                case LUANCH_WEIXIN:
                    AppUtils.openApp(FeiLongService.this, "微信");
                    break;
                case REQUEST_BLUETOOCH:
                    Log.d(TAG, "handleMessage: ");
//                    connectDevice();
                    break;
                case RECOGNITIONMODEL:
                    Log.d(TAG, "handleMessage: RECOGNITIONMODEL show()--");
                    recognitionModel();
                    break;
                case AWAKEMODEL:
                    awakeModel();
                    break;
                case SET_VOLUME:
                    if (null != floatingView) {
//                        Log.d(TAG, "handleMessage: msg.arg1*2="+msg.arg1*1.2);
                        floatingView.setVolume((int) (msg.arg1 * 2.3));
                    }
                    break;
                case LOCAL_FEILONG_NOT_RESPONE:
                case CLOSE_VOICE_LAYOUT:
                    Log.e(TAG, "handleMessage:CLOSE_VOICE_LAYOUT " + tag);
                    handler.removeMessages(CLOSE_VOICE_LAYOUT);
                    if (null != floatingView) {
                        floatingView.setAskViewText("");
                        floatingView.hide();
//                        handler.sendEmptyMessageDelayed(TCP_CHECK, 15000);
                    }
                    if (null != cancelable) {
                        cancelable.cancel();
                    }
                    break;
                case RESTART_VOICE:
                    initAbility();
                    break;
            }
        }

        MainViewModel viewModel = new MainViewModel();
    };

    private void recognitionModel() {
        if (null != floatingView
                && !"weixincontent".equals(feilongRespone.getIntent())
                && !"sendhongbao".equals(feilongRespone.getIntent())
                && !"sendweixin".equals(feilongRespone.getIntent())
        ) {
            if (!floatingView.isShowing()) {
                floatingView.show();
                Log.d(TAG, "recognitionModel: floatingView.show();");
                EventBus.getDefault().post(new FloatViewState(true));
            }
            floatingView.hideInteractiveLayout();
            floatingView.recognitionModel();
        }
    }

    private void awakeModel() {
        if (null != floatingView
                && !"weixincontent".equals(feilongRespone.getIntent())
                && !"sendhongbao".equals(feilongRespone.getIntent())
                && !"sendweixin".equals(feilongRespone.getIntent())
        ) {
            Log.d(TAG, "awakeModel()floatingView.isShowing()= " + floatingView.isShowing());
            if (!floatingView.isShowing()) {
                floatingView.show();
                Log.d(TAG, "awakeModel: floatingView.show();");
                EventBus.getDefault().post(new FloatViewState(true));
            }
//            floatingView.hideInteractiveLayout();
            floatingView.awakeModel(SPUtils.getInstance().getInt(AI_MODE));
        }
    }

    private String deviceName;

    private void connectDevice() {
//        if(1==1)return;
        Log.d(TAG, "connectDevice:>> ");
        ECBLE.openBluetoothAdapter(this);
        ECBLE.startBluetoothDevicesDiscovery(this);
        String deviceMac = SPUtils.getInstance().getString(ECBLE.DEVICE_MAC);
        deviceName = SPUtils.getInstance().getString(ECBLE.DEVICE_NAME);
        Log.d(TAG, "connectDevice: deviceMac=" + deviceMac);
        Log.d(TAG, "connectDevice: deviceName=" + deviceName);
        BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
        if (blueAdapter != null && blueAdapter.isEnabled() && !TextUtils.isEmpty(deviceMac)) {
            ECBLE.createBLEConnection(FeiLongService.this, deviceMac);
        }

        ECBLE.onBluetoothDeviceFound(new ECBluetoothDeviceFoundCallback() {
            @Override
            public void callback(String id, String name, String mac, int rssi) {
//                Log.e(TAG, name + "|" + mac + "|" + rssi);
                if (mac.equals(deviceMac)) {
                    ECBLE.createBLEConnection(FeiLongService.this, mac);
                    ECBLE.stopBluetoothDevicesDiscovery(FeiLongService.this);
                }
            }
        });
        ECBLE.onBLEConnectionStateChange(new ECBLEConnectionStateChangeCallback() {
            @Override
            public void callback(boolean ok, int errCode, String errMsg) {
                Log.d(TAG, "callback: BluetoothProfile connect=" + ok + "  unSendAllGoData=" + unSendAllGoData);
//                EventBus.getDefault().post(new BlueConnect());
                connectAllGo = ok;
                if (ok) {
                    if (!TextUtils.isEmpty(unSendAllGoData)) {
                        handler.removeMessages(SEND_UNSEND_BLUETOOCH);
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
//                                setSendUnsendBluetooch();
                                Log.d(TAG, "run: 发送unSendAllGoData=" + unSendAllGoData);
                            }
                        }, 300);
                    }
//                    EventBus.getDefault().post(new BlueToothMsg(str,strHex));
                    Log.d(TAG, "callback: deviceId=" + deviceMac);
                } else {
                    ToastUtils.showShort(getString(R.string.connect_bluetooch_fail));
                    ECBLE.onBLECharacteristicValueChange((str, strHex) -> {
                    });
                    ECBLE.onBLEConnectionStateChange((ok1, errCode1, errMsg1) -> {
                    });
                    ECBLE.closeBLEConnection();
                }
            }
        });
       /* ECBLE.onBLECharacteristicValueChange(new ECBLECharacteristicValueChangeCallback() {
            @Override
            public void callback(String str, String strHex) {
                Log.d(TAG, "callback: str=" + str + " strHex=" + strHex);
                EventBus.getDefault().post(new BlueToothMsg(str, strHex));
                Log.d(TAG, "callback: post(new BlueToothMsg");
            }
        });*/
    }

    private void setSendUnsendBluetooch() {
        handler.removeMessages(SEND_UNSEND_BLUETOOCH);
        if (TextUtils.isEmpty(unSendAllGoData)) return;
        Log.d(TAG, "run: ECBLE.writeBLECharacteristicValue setSendUnsendBluetooch");
        ECBLE.writeBLECharacteristicValue(unSendAllGoData, "hex".equals(isHex));
        handler.sendEmptyMessageDelayed(SEND_UNSEND_BLUETOOCH, 400);
    }

    private boolean connectAllGo;
    public static boolean hasConnect = false;
    private MusicPlayer musicPlayer = new MusicPlayer(this);
    private boolean hasOpenExagear;
    private int ttsType;
    public static FeilongRespone feilongRespone = new FeilongRespone();

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TtsMsg ttsMsg) throws RemoteException {
        ttsHelpers.startTTS(ttsMsg.getTtsMsg(), TEXT_TYPE);
    }

    /**
     * 蓝牙状态变化
     *
     * @param blueToochEnable
     * @throws RemoteException
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(BlueToochEnable blueToochEnable) throws RemoteException {
        handler.removeMessages(REQUEST_BLUETOOCH);
        handler.sendEmptyMessageDelayed(REQUEST_BLUETOOCH, 250);
        connectDevice();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CopyFile event) throws RemoteException {
        initAbility();
    }

    //讯飞出错，停止识别
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(IflytekError event) throws RemoteException {
        ivwHelper.stopIvw();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NoticeMsg noticeMsg) throws RemoteException {
        FeilongRespone request = new FeilongRespone("0", "comingmsg");
        request.setFrom(noticeMsg.getFrom());
        request.setName(noticeMsg.getName());
        request.setMsg(noticeMsg.getText());
        request.setType(noticeMsg.getType());
        TcpClient.sendTcpMessage(new Gson().toJson(request));
        Log.d(TAG, "onEventMainThread: NoticeMsg=" + new Gson().toJson(request));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotificationText message) throws RemoteException {
        Log.d(TAG, "NotificationText: " + message.getText());
        ttsHelpers.startTTS(message.getText(), -1);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TcpUpdateFeiLong message) throws RemoteException {
        updateFeilong();
    }

    //开始识别
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(StartVoice startVoice) throws RemoteException {
        int language = SPUtils.getInstance().getInt(SettingActivity.SELECT_LANGUAGE, 0);
        startSpeechRecognition();
        recognitionModel();
    }

    public class MyBinder extends Binder {
        // 获取BindService实例
        public FeiLongService getService() {
            return FeiLongService.this;
        }
    }

    private MyBinder binder = new MyBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Commands command) throws RemoteException {
        handler.sendEmptyMessage(AWAKEMODEL);
        musicPlayer.stop();
        if (command.getCommand().equals("停止报警")) {
        } else {
            sendToFeiLongByUI(command.getCommand());
        }
        floatingView.setAskViewText(command.getCommand());
        isToggle = true;
    }


    private void updateFeilong() {
        TCPFileClient client = new TCPFileClient();
        client.startClient(new TCPFileClient.OnSendFileCompleteListener() {
            @Override
            public void onSendFileComplete() {
//                sendToFeiLongByIntent("exit");
//                EventBus.getDefault().post(new ShowDownLoadDialog(false, getString(R.string.init_xxz)));
                EventBus.getDefault().post(new ShowDownLoadDialog(false, "理解引擎更新已完成，请重启手机使之生效"));
                AppUtils.forceStopPackage(FeiLongService.this, AewmeService.EXAGEAR_PKG);
                Intent intent = new Intent("com.termux");
                sendBroadcast(intent);
            }

            @Override
            public void onSendFileFailure() {

            }
        });
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                client.sendTcpMessage();
                client.sendTcpFile("/sdcard/exagear.zip");

            }
        }, 1000);
    }

    //用户手动关闭唤醒功能
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(UserStopWakeUp awake) throws RemoteException {
        SPUtils.getInstance().put(WAKEUP_STATE, awake.getState());
        if (awake.getState()) {
            startAwake();
        } else {
            stopVoice();
        }
    }

    //修改唤醒词后重新开启唤醒
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ResetAwakeWords awake) throws RemoteException {
        Log.d(TAG, "onEventMainThread: " + awake);
//        ivwHelper.pauseRecord();
        ivwHelper.stopIvw();
        startAwake();
//        ivwHelper.resumeRecord();
//        ivwHelper.resumeRecord();
//        initVoice();
    }

    /**
     * 开始唤醒
     */
    private void startAwake() {
        if (SPUtils.getInstance().getBoolean(WAKEUP_STATE)) {
            ivwHelper.startIvw();
            ivwHelper.startRecord();
        }
    }

    private DeviceListActivity.DeviceInfo currentDevice;

    //收到蓝牙设备连接
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DeviceListActivity.DeviceInfo deviceInfo) throws RemoteException {
        if (!TextUtils.isEmpty(deviceInfo.getName())) {
            ECBLE.createBLEConnection(this, deviceInfo.getId());
            currentDevice = deviceInfo;
            SPUtils.getInstance().put(ECBLE.DEVICE_MAC, currentDevice.getId());
            SPUtils.getInstance().put(ECBLE.DEVICE_NAME, currentDevice.getName());
        }
    }

    public static final String DEVICE_UD = ",ud#";

    /**
     * 初始化allgo给理解模块
     *
     * @param name
     */
    private void initAllGo(String name) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        FeilongRespone feilongRespone = new FeilongRespone("0", "btinit");
        feilongRespone.setSN(name);
        TcpClient.sendTcpMessage(gson.toJson(feilongRespone));
        Log.d(TAG, "初始化allgo： " + gson.toJson(feilongRespone));
    }

    //处理收到的蓝牙信息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(BlueToothMsg message) throws RemoteException {
        Log.d(TAG, "onEventMainThread str=" + message.getStr() + " --strHex--" + message.getStrHex());
//        if (message.getStr().equalsIgnoreCase(unSendAllGoData)) {
        handler.removeMessages(SEND_UNSEND_BLUETOOCH);
        unSendAllGoData = "";
//        }
        handleBlueToothMsg(message);
    }

    //处理收到的蓝牙信息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(BlueConnect message) throws RemoteException {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (TextUtils.isEmpty(deviceName)) {
                    deviceName = SPUtils.getInstance().getString(ECBLE.DEVICE_NAME);
                }
                initAllGo(deviceName);
            }
        }, 500);
    }

    /**
     * 处理收到的蓝牙消息
     *
     * @param message
     */
    private void handleBlueToothMsg(BlueToothMsg message) {
        String str = message.getStr();
        if (null == str) {
            return;
        }
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        Log.d(TAG, "onEventMainThread: currentDevice=" + currentDevice);
//        if (str.endsWith(DEVICE_UD)) {
//            if (null != currentDevice && currentDevice.getName().contains(str.replace(DEVICE_UD, "").replace("=", ""))) {
//                FeilongRespone feilongRespone = new FeilongRespone("0", "btinit");
//                feilongRespone.setSN(currentDevice.getName());
//                TcpClient.sendTcpMessage(gson.toJson(feilongRespone));
//                SPUtils.getInstance().put(ECBLE.DEVICE_MAC, currentDevice.getId());
//                String deviceMac = SPUtils.getInstance().getString(ECBLE.DEVICE_MAC);
//                Log.d(TAG, "BlueToothMsg: deviceMac=" + deviceMac);
//                SPUtils.getInstance().put(ECBLE.DEVICE_NAME, currentDevice.getName());
//                Log.d(TAG, "handleBlueToothMsg： " + gson.toJson(feilongRespone));
//            }
//        } else {
        FeilongRespone feilongRespone = new FeilongRespone("0", "btrecev");
        String deviceName = SPUtils.getInstance().getString(ECBLE.DEVICE_NAME);
        feilongRespone.setSN(deviceName);
        feilongRespone.setData(message.getStr());
        feilongRespone.setDatatype(message.getDatatype());
        TcpClient.sendTcpMessage(gson.toJson(feilongRespone));
        Log.d(TAG, "发送给理解： " + gson.toJson(feilongRespone));
//        }
    }

    private static final String ACTION_OPEN = "已开启";
    private static final String ACTION_CLOSE = "已关闭";
    private String currentMode;
    private String unSendAllGoData;
    private String isHex;

    /**
     * 启动wine环境
     */
    private void startWine() {
        boolean exaAlive = AppUtils.checkAlive(this, AewmeService.TERMUX_PKG);
        Log.d(TAG, "startWine: exaAlive=" + exaAlive);

//        boolean install = AppUtils.startExagear1(this);
        boolean install = AppUtils.startTermux(this);
        if (!install) return;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
//                AppUtils.goHome(FeiLongService.this);
            }
        }, 400);
    }

    private int count;

    /**
     * 处理收到离线理解发来的消息
     *
     * @param message
     * @throws RemoteException
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageClient message) throws RemoteException {
        String content = message.getData();
        Log.d(TAG, "onEventMainThread: data=" + content);
        if ((TextUtils.isEmpty(content) || content.length() < 4) && System.currentTimeMillis() - lastRequestTime < 5000) {
//            EventBus.getDefault().post(new GlobalEvent(currentRequest));
        }
        if (content.equals("error")) {//没有连上离线理解,每隔2秒连接一次
            Log.e(TAG, "onEventMainThread: 飞龙码连接断开");
            handler.sendEmptyMessageDelayed(CONNECT_FEILONG, 2000);
            if (count == 0) {
                startWine();
            }
            count++;
            if (count > 10) {
                count = 0;
            }
            hasConnect = false;
            return;
        } else if ("success".equals(content)) {//已经连上离线理解,每秒发一次心跳
            handler.sendEmptyMessageDelayed(TCP_CHECK, 1000);
            AppUtils.initFeilong();
            hasOpenExagear = true;
//            if (!TextUtils.isEmpty(undoString)) {
//                sendToTcp(undoString);
//            }
        }
        hasConnect = true;
        if (content.length() < 10) {
            return;
        }
//        FileUtil.appendText(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "receive_feilong_result.txt", content);
        undoString = "";
        try {
            feilongRespone = new Gson().fromJson(content, FeilongRespone.class);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        hasOpenExagear = true;
        if (null == feilongRespone || null == ivwHelper) return;
        if ("none".equals(feilongRespone.getTarget())) {//跟理解端的心跳数据
            return;
        }
        ttsType = TTSHelper.TEXT_TYPE;
        handler.removeMessages(LOCAL_FEILONG_NOT_RESPONE);
        handler.removeMessages(CLOSE_VOICE_LAYOUT);
        handler.removeMessages(CHECK_EXAGEAR);
        handler.removeMessages(CONNECT_FEILONG);

        stopSpeechRecognition();
        currentMode = feilongRespone.getMode();

        if (getString(R.string.scan).equals(feilongRespone.getFun())) {//扫一扫
            if (getString(R.string.wechat).equals(feilongRespone.getTarget())) {
                AppUtils.openWeChatScan(this);
            } else {
                AppUtils.openZhiFuBaoScan(this);
            }
        }
        if ("chkif".equals(feilongRespone.getType())) {//需要请求在线问答
//            String phone = feilongRespone.getPhoneno();
//            if (TextUtils.isEmpty(phone)) {
//                phone = "12345678900";
//            }
//            getTalk(feilongRespone.getInput(), "86" + phone);

//            EventBus.getDefault().post(new StartTextAIUI(feilongRespone.getInput()));
            if (ONLINE_AI != SPUtils.getInstance().getInt(AI_MODE)) {
                EventBus.getDefault().postSticky(new AIUIMsg("主人，您好！我是您的私人AI助理，离线AI机器人，可以帮主人您做事，帮您操作，还可以帮您记忆提醒。您刚刚这问题呢，可以问小飞在线AI服务机器人哦！"));
            }
            return;
        }
        switch (feilongRespone.getIntent()) {
            case "init"://连上理解后收到初始化的数据，保存离线理解的当前版本号
                String feilongVersion = feilongRespone.getVer();
                if (!TextUtils.isEmpty(feilongVersion)) {
                    SPUtils.getInstance().put(SettingActivity.FEILONG_VERSION_NAME, feilongVersion);
                }
                String feilongCode = feilongRespone.getvCode();
                if (!TextUtils.isEmpty(feilongCode)) {
                    SPUtils.getInstance().put(SettingActivity.FEILONG_VERSION_CODE, feilongCode);
                }

                return;
            case "ppchat":
                if ("语音电话".equals(feilongRespone.getType()) || "語音電話".equals(feilongRespone.getType())) {
                    PPMessage ppMessage = new PPMessage();
                    ppMessage.setType(1);
                    ppMessage.setName(feilongRespone.getName());
                    EventBus.getDefault().post(ppMessage);
                } else if ("视频电话".equals(feilongRespone.getType()) || "視頻電話".equals(feilongRespone.getType())) {
                    PPMessage ppMessage = new PPMessage();
                    ppMessage.setType(2);
                    ppMessage.setName(feilongRespone.getName());
                    EventBus.getDefault().post(ppMessage);
                }
                break;
            case "sendPP"://发pp消息
                PPMessage ppMessage = new PPMessage();
                ppMessage.setType(0);
                ppMessage.setMessage(feilongRespone.getPPcontent());
                ppMessage.setName(feilongRespone.getTarget1());
                EventBus.getDefault().post(ppMessage);
                break;
            case "setaimode"://切换模式
                EventBus.getDefault().post(new Setaimode(feilongRespone.getMode()));

                break;
            case "clearsysmem"://清除内存
                AppUtils.clearMemory(this);
                break;
            case "alarm"://紧急报警
                alertAlarmView.show();
                break;
            case "showlist"://查看已保存的列表（电话、记忆、提醒）
                goRemindList();
                handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
                break;
            case "close_wakeup"://关闭语音唤醒
                EventBus.getDefault().post(new CloseVoice());
                stopVoice();
                break;
            case "startfunc"://开始拍照
                if (getString(R.string.take_photo).equals(feilongRespone.getTarget())) {//拍照
                    AppUtils.startAppByPackageName(this, "com.freeme.camera");
                    handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
                }
                break;
            case "screenoff"://设置息屏时间
                if (!TextUtils.isEmpty(feilongRespone.getTime())) {
                    AppUtils.setSleepTime(this, TextUtil.getScreenOffTime(feilongRespone.getTime()));
                }
                break;
            case "btsend"://发送蓝牙指令控制allgo家居设备
                String btData = (String) feilongRespone.getData();
                if (btData.contains("999999999,SV#") || btData.contains("111111111,J") || btData.contains(",a")) {//把未发送成功的保存起来，重新连接蓝牙再发送（999999999,SV#是初始化语句）
                    /*if(TextUtils.isEmpty(deviceName)){
                        deviceName = SPUtils.getInstance().getString(ECBLE.DEVICE_NAME,"");
                    }
                    String sn = "="+deviceName.replace("AllGo_FN","")+",v66#";
                    BlueToothMsg blueToothMsg = new BlueToothMsg();
                    blueToothMsg.setStr(sn);
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            handleBlueToothMsg(blueToothMsg);
                        }
                    }, 200);*/

                } else {
//                    unSendAllGoData = btData;
                    isHex = feilongRespone.getDatatype();
                    resendTime = 0;
                    blueConnectTime = 0;
                }
                if (btData.contains("=,a")) {
                    if (TextUtils.isEmpty(deviceName)) {
                        deviceName = SPUtils.getInstance().getString(ECBLE.DEVICE_NAME, "");
                    }
                    btData = "=" + deviceName.replace("AllGo_FN", "") + btData.substring(1);
                }
                if (connectAllGo) {//已连接allgo
                    Log.d(TAG, "发送蓝牙指令: btsend=" + btData + "  =isHex=" + "hex".equals(isHex));
                    ECBLE.writeBLECharacteristicValue(btData, "hex".equals(isHex));
                    Log.d(TAG, "run: ECBLE.writeBLECharacteristicValue connectAllGo");
                    handler.sendEmptyMessageDelayed(SEND_UNSEND_BLUETOOCH, 400);
                } else {//未连接时重新打开蓝牙，自动扫描并连接allgo
                    reConnectBlueTooch();
                    String finalBtData = btData;
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "run: ECBLE.writeBLECharacteristicValue postDelayed");
                            ECBLE.writeBLECharacteristicValue(finalBtData, "hex".equals(isHex));
                        }
                    }, 5000);
                }
                break;
            case "setmode"://设置唤醒模式
                if ("1".equals(feilongRespone.getMode())) {
                    interactionMode = true;//连续唤醒模式
                } else {
                    interactionMode = false;
                }
                ttsHelpers.startTTS(feilongRespone.getMsg(), TTSHelper.AWAKE_ONE_TYPE);
                break;
            case "guide"://高德导航
                AppUtils.openGaode(this, feilongRespone.getTarget());
                break;
            case "TTS":
//                if (!TextUtils.isEmpty(feilongRespone.getText()) && TextUtil.hasChar(feilongRespone.getText())) {
//                    feilongRespone.setText("好的");
//                }
                if (feilongRespone.getText().equals("好的，在线机器人聊天助理为您服务！")) {
                    feilongRespone.setText("好的，在线机器人聊天助理为您服务！\n主人，您请说：");
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            floatingView.recognitionModel();
                        }
                    }, 4000);
                } else if (feilongRespone.getText().equals("好的，离线机器人服务助理为您服务！")) {
//                    feilongRespone.setText("好的，离线机器人服务助理为您服务!\n主人，您请说：");
//                    feilongRespone.setText("我在");
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
//                            floatingView.recognitionModel();
                            startOnce();
                        }
                    }, 4000);
                }

                break;
            case "openapp"://打开App
                if (getString(R.string.wechat_pyq).equals(feilongRespone.getTarget())) {
                    AppUtils.startApp(this, WeChatTextWrapper.WECAHT_PACKAGENAME, WeChatTextWrapper.WechatClass.WECHAT_CLASS_SNSTIMELINE);
                } else {
                    AppUtils.openApp(this, feilongRespone.getTarget());
                }

                break;
            case "closeapp"://关闭App
                if ("WIFI".equals(feilongRespone.getTarget())) {
                    EdgeManager.getInstance().wifiNetwork(false);
                } else {
                    AppUtils.goHome(this);
                }
                break;
            case "music"://播放本地歌曲
                LinkedTreeMap<String, String> map1 = (LinkedTreeMap<String, String>) feilongRespone.getData();
                if (null != map1 && map1.containsKey("keyword")) {
                    String musicName = map1.get("keyword");
                    String path = null;
                    if (getString(R.string.slowly_music).equals(musicName)) {
                        path = MusicPlayer.getSleepMusic();
                    } else {
                        path = MusicPlayer.getMusic(musicName);
                    }
                    if (TextUtils.isEmpty(path)) {
                        ttsHelpers.startTTS(feilongRespone.getMsg(), ttsType);
                        floatingView.setAnswerViewText(feilongRespone.getMsg());
                        Log.e(TAG, "onEventMainThread: 找不到本地歌曲");
                    } else {
                        floatingView.playMusic(path);
                    }
                }
                break;
            case "syncphone"://同步电话号码
                String number = feilongRespone.getPhonenum();
                String contactId = AppUtils.getContactId(this, feilongRespone.getName());
                if (TextUtils.isEmpty(contactId)) {
                    AppUtils.insertContact(this, feilongRespone.getName(), number);
                } else {
                    AppUtils.updateContact(this, contactId, number);
                }
                break;
            case "call"://打电话给某人
                String phone = feilongRespone.getPhonenum();
                if (TextUtils.isEmpty(phone)) {
                    phone = AppUtils.getPhoneNumberByName(this, feilongRespone.getName());
                }
                if (TextUtils.isEmpty(phone)) {
                    phone = AppUtils.getPhoneNumberByPinyin(this, TextUtil.getPinyin(feilongRespone.getName()));
                }
                if (TextUtils.isEmpty(phone)) {
                    ttsHelpers.startTTS("找不到联系人", ttsType);
                } else {
                    AppUtils.callPhone(this, phone);
                }
                break;
            case "weixincontent"://发送微信内容
                handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
                AewmeService.weixinType = AewmeService.WEIXIN_MSG;
                AewmeService.weixinHandle = true;
                if (AewmeService.contentPackageName.equals(WeChatTextWrapper.WECAHT_PACKAGENAME) || AewmeService.currentActivity.startsWith(WeChatTextWrapper.WECAHT_PACKAGENAME)) {
                    EventBus.getDefault().post(new WeixinMsg(AewmeService.WEIXIN_MSG, (String) feilongRespone.getData()));
                } else {
                    AppUtils.openApp(this, getString(R.string.wechat));
                }

                break;
            case "sendSMS"://发送短信
                userPhone = feilongRespone.getPhonenno();
                if (TextUtils.isEmpty(userPhone)) {
                    userPhone = AppUtils.getPhoneNumberByName(this, feilongRespone.getTarget1());
                    Log.d(TAG, "onEventMainThread: getPhoneNumberByName");
                }

                if (TextUtils.isEmpty(userPhone)) {
                    userPhone = AppUtils.getPhoneNumberByPinyin(this, feilongRespone.getTarget());
                    Log.d(TAG, "onEventMainThread: getPhoneNumberByPinyin");
                }

                if (TextUtils.isEmpty(userPhone)) {
                    ttsHelpers.startTTS("找不到号码", TTSHelper.TEXT_TYPE);
                    return;
                }
                String SMSContent = feilongRespone.getSMScontent();
                if (TextUtils.isEmpty(address)) {
                    address = SPUtils.getInstance().getString("address");
                }

                if (TextUtils.isEmpty(feilongRespone.getSMScontent())) {
                    ttsHelpers.startTTS(feilongRespone.getMsg(), TTSHelper.AWAKE_TYPE);
                } else {
                    ttsHelpers.startTTS(feilongRespone.getMsg(), TTSHelper.TEXT_TYPE);
                    AppUtils.sendSms(this, userPhone, SMSContent);
                    if (null != feilongRespone.getSMScontent() && (feilongRespone.getSMScontent().contains("报！警！") || feilongRespone.getSMScontent().contains("報！警！"))) {
                        String msg = longitude + "-" + latitude + " " + address;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                AppUtils.sendSms(FeiLongService.this, userPhone, msg);
                            }
                        }, 500);
                    }
                    Log.d(TAG, "onEventMainThread:userPhone= " + userPhone);
                    Log.d(TAG, "onEventMainThread:SMSContent= " + SMSContent);
                }
                break;
            case "SMScontent"://发送短信内容
                if (!TextUtils.isEmpty(userPhone)) {
                    AppUtils.sendSms(this, userPhone, (String) feilongRespone.getData());
                    ttsHelpers.startTTS("已发送", ttsType);
                }
                break;
            case "sendhongbao":
            case "sendweixin"://发送微信红包或消息，启动微信
                handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
//                ttsHelpers.startTTS("好的", TTSHelper.WX_TYPE);
                if (TextUtils.isEmpty(feilongRespone.getWeixincontent())) {
                    currentTTS = feilongRespone.getMsg();
                } else {
                    currentTTS = "";
                }
                //
                if (AewmeService.currentActivity != null && AewmeService.currentActivity.startsWith(WeChatTextWrapper.WECAHT_PACKAGENAME)
                        && !WeChatTextWrapper.WechatClass.WECHAT_CLASS_LAUNCHUI.equals(AewmeService.currentActivity)
                ) {
                    EventBus.getDefault().post(new WechatHome());
                } else {
                    startWechat();
                }
                break;
            case "searchapp":
                switch (feilongRespone.getTarget()) {
                    case "淘宝":
                    case "淘寶"://例：去淘宝搜索三百块以下的鞋子
                        AewmeService.searchKey = feilongRespone.getKeyword();
                        AppUtils.startApp(this, "com.taobao.taobao", "com.taobao.search.searchdoor.SearchDoorActivity");
                        break;
                    case "百度":
                        AppUtils.searchBaidu(this, feilongRespone.getKeyword());
                        handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
                        break;
                }
                break;
            case "volume":
//                VoiceControl voiceControl = (VoiceControl) feilongRespone.getData();
                LinkedTreeMap<String, String> map = (LinkedTreeMap<String, String>) feilongRespone.getData();
                switch (map.get("action")) {
                    case "incparm"://增大音量
                        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
                        break;
                    case "decparm"://调小音量
                        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
                        break;
                    case "setmin"://音量最小
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVol / 5, AudioManager.FLAG_PLAY_SOUND);
                        break;
                    case "setmax"://音量最大
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVol, AudioManager.FLAG_PLAY_SOUND);
                        break;
                    case "set"://设置音量值
                        int volume = Integer.valueOf(map.get("vol"));
                        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume * maxVol / 100, AudioManager.FLAG_PLAY_SOUND);
                        Log.d(TAG, "onEventMainThread: " + (volume * maxVol / 100));
                        break;
                }
                ttsHelpers.startTTS(feilongRespone.getMsg(), ttsType);
//                Log.d(TAG, "onEventMainThread: voiceControl="+voiceControl.getAction());
                break;
            case "opensysfun"://打开系统功能（系统语言设置繁体，理解也会返回繁体）
                switch (feilongRespone.getTarget()) {
                    case "重开机":
                    case "重開機":
                        EdgeManager.getInstance().reboot();
                        break;
                    case "静音":
                    case "靜音":
                        EdgeManager.getInstance().openMute();
                        break;
                    case "移动网络":
                    case "移動網絡":
                        invokeSystemSetting(AppConstant.OPEN_MOBILE_NETWORK);
                        break;
                    case "数据漫游":
                    case "數據漫遊":
                        invokeSystemSetting(AppConstant.OPEN_ROAMING_DATA);
                        break;
                    case "地理位置":
                        invokeSystemSetting(AppConstant.OPEN_GPS);
                        break;
                    case "手机热点":
                    case "手機熱點":
                        invokeSystemSetting(AppConstant.OPEN_HOTSPOT);
                        break;
                    case "省电模式":
                    case "省電模式":
                        invokeSystemSetting(AppConstant.OPEN_POWER_SAVING);
                        break;
                    case "WIFI":
                    case "无线网络":
                    case "無線網絡":
                        EdgeManager.getInstance().wifiNetwork(true);
                        ttsHelpers.startTTS(ACTION_OPEN, ttsType);
                        break;
                    case "蓝牙":
                    case "藍牙":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getBluetoothState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            Log.d(TAG, "onEventMainThread: result=" + result);
                            ttsHelpers.startTTS(feilongRespone.getTarget() + result, ttsType);
                        } else {
                            EdgeManager.getInstance().openBluetooth();
                        }
                        break;
                    case "自动亮度":
                    case "自動亮度":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getAutomaticBrightnessState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            ttsHelpers.startTTS(feilongRespone.getTarget() + result, ttsType);
                        } else {
                            EdgeManager.getInstance().openAutomaticBrightness();
                        }
                        break;
                    case "护眼模式":
                    case "護眼模式":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getEyeProtectionModeState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            ttsHelpers.startTTS(feilongRespone.getTarget() + result, ttsType);
                        } else {
                            EdgeManager.getInstance().eyeProtectionModeSwitch(true);
                        }
                        break;
                    case "深色模式":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getDarkModeState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            ttsHelpers.startTTS(feilongRespone.getTarget() + result, ttsType);
                        } else {
                            EdgeManager.getInstance().darkModeSwitch(true);
                        }
                        break;
                    case "飞行模式":
                    case "飛行模式":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getAirplaneModeState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            ttsHelpers.startTTS(feilongRespone.getTarget() + result, ttsType);
                        } else {
                            EdgeManager.getInstance().airplaneModeSwitch(true);
                        }
                        break;
                    case "手电筒":
                    case "手電筒":
                        EdgeManager.getInstance().flashlightSwitch(true);
                        break;
                }
                break;
            case "setsysfun":
                if (getString(R.string.screen).contains(feilongRespone.getMode()) || getString(R.string.brightness).contains(feilongRespone.getMode())) {
                    switch (feilongRespone.getAction()) {
                        case "incparm"://屏幕亮度调大
                            EdgeManager.getInstance().inScreenBrightness();
                            break;
                        case "decparm"://屏幕亮度调小
                            EdgeManager.getInstance().deScreenBrightness();
                            break;
                        case "set"://屏幕亮度调到特定值
                            int value = (int) (Integer.valueOf(feilongRespone.getVol()) * 2.55);
                            EdgeManager.getInstance().setScreenBrightness(value);
                            break;
                        case "setmax"://屏幕亮度调到最大
                            EdgeManager.getInstance().setScreenBrightness(255);
                            break;
                        case "setmin"://屏幕亮度调最小
                            EdgeManager.getInstance().setScreenBrightness(10);
                            break;
                    }
                }
                break;
            case "closesysfun"://关闭系统功能
                switch (feilongRespone.getTarget()) {
                    case "静音":
                    case "靜音":
                        EdgeManager.getInstance().closeMute();
                        break;
                    case "手机屏幕":
                    case "手機屏幕":
                        AppUtils.execKeyevent("223");//息屏
                        break;
                    case "移动网络":
                    case "移動網絡":
                        invokeSystemSetting(AppConstant.CLOSE_MOBILE_NETWORK);
                        break;
                    case "数据漫游":
                    case "數據漫遊":
                        invokeSystemSetting(AppConstant.CLOSE_ROAMING_DATA);
                        break;
                    case "省电模式":
                    case "省電模式":
                        invokeSystemSetting(AppConstant.CLOSE_POWER_SAVING);
                        break;
                    case "地理位置":
                        invokeSystemSetting(AppConstant.CLOSE_GPS);
                        break;
                    case "手机热点":
                    case "手機熱點":
                        invokeSystemSetting(AppConstant.CLOSE_HOTSPOT);
                        break;
                    case "WIFI":
                    case "无线网络":
                    case "無線網絡":
                        EdgeManager.getInstance().wifiNetwork(false);
                        break;
                    case "蓝牙":
                    case "藍牙":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getBluetoothState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            feilongRespone.setText(result);
                        } else {
                            EdgeManager.getInstance().closeBluetooth();
                        }
                        break;
                    case "自动亮度":
                    case "自動亮度":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getAutomaticBrightnessState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            feilongRespone.setText(result);
                        } else {
                            EdgeManager.getInstance().closeAutomaticBrightness();
                        }
                        break;
                    case "护眼模式":
                    case "護眼模式":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getEyeProtectionModeState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            feilongRespone.setText(result);
                        } else {
                            EdgeManager.getInstance().eyeProtectionModeSwitch(false);
                        }
                        break;
                    case "深色模式":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getDarkModeState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            feilongRespone.setText(result);
                        } else {
                            EdgeManager.getInstance().darkModeSwitch(false);
                        }
                        break;
                    case "飞行模式":
                    case "飛行模式":
                        if ("yes".equals(feilongRespone.getQuery())) {
                            boolean isValid = EdgeManager.getInstance().getAirplaneModeState();
                            String result = isValid ? ACTION_OPEN : ACTION_CLOSE;
                            feilongRespone.setText(result);
                        } else {
                            EdgeManager.getInstance().airplaneModeSwitch(false);
                        }
                        break;
                    case "手电筒":
                    case "手電筒":
//                        if("yes".equals(feilongRespone.getQuery())){
//                            boolean isValid = EdgeManager.getInstance().getFlashlightState();
//                            String result = isValid?ACTION_OPEN:ACTION_CLOSE;
//                            ttsHelpers.startTTS(result, ttsType);
//                        }else{
                        EdgeManager.getInstance().flashlightSwitch(false);
//                        }
                        break;
                }
                break;
            case "temp_update"://测试理解功能的升级
                EventBus.getDefault().post(new TestXxzUpdate());
                handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
                break;
        }
        if ("tts_end".equals(feilongRespone.getMode())) {
//            listenBook();
            ttsType = TTSHelper.BOOK_TYPE;
        }
//        myBinder.sendMessage(respone.getIntent(), respone.getTarget());
        String text = feilongRespone.getText();
//        if (TextUtils.isEmpty(text)) {
//            text = feilongRespone.getMsg();
//        }
        if ("yes".equals(feilongRespone.getQuery())) {
            return;
        }
        //识别是英文，先翻译再发给理解
        if ("EN".equals(feilongRespone.getLanguage()) && !TextUtils.isEmpty(text)) {
            transHelper.translate(TransHelper.CNEN, text);
            return;
        }
        String answer = text;
        if (!TextUtils.isEmpty(text)) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    awakeModel();
                    Log.d(TAG, "run: setAnswerViewText");
                    floatingView.setAnswerViewText(answer);
                }
            });
            handler.removeMessages(CLOSE_VOICE_LAYOUT);

            if ("EN2".equals(feilongRespone.getLanguage())) {
                ttsHelpers.startTTS(text, ttsType, LANGUAGE_EN_TYPE);
                return;
            }
            Log.d(TAG, "onEventMainThread: handler.removeMessages(CLOSE_VOICE_LAYOUT)--;");
            text = text.replaceAll("\n", "").replaceAll(" ", "").replaceAll("\r", "").replaceAll("\r", "");
            if ("tts_end".equals(feilongRespone.getMode())) {
                float scale = SPUtils.getInstance().getFloat(TTS_SCALE, 1);
                Log.d(TAG, "onEventMainThread:scale= " + scale);
                ttsHelpers.setSpeed((int) (TTSHelper.STAND_SPEED * scale));
            } else {
                ttsHelpers.setSpeed((int) (TTSHelper.STAND_SPEED * 1));
            }
            ttsHelpers.startTTS(text, ttsType);
        }
    }

    private void reConnectBlueTooch() {
        if (blueConnectTime >= 2) {
            handler.removeMessages(SEND_UNSEND_BLUETOOCH);
            return;
        }
        blueConnectTime++;
        Log.d(TAG, "reConnectBlueTooch:>> reConnectTime>>=" + blueConnectTime);

        EdgeManager.getInstance().closeBluetooth();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                permissionsBlueToochInit(true);
            }
        }, 400);
    }

    /**
     * 启动微信
     */
    private void startWechat() {
        if (!"sendweixin".equals(feilongRespone.getIntent()) && !"sendhongbao".equals(feilongRespone.getIntent())) {
            return;
        }
        WechatUtils.MSG_CONTENT = feilongRespone.getWeixincontent();
        AewmeService.weixinType = AewmeService.WEIXIN_FIND_NAME;
        AewmeService.weixinHandle = true;
        WechatUtils.FRIEND_NAME = feilongRespone.getTarget1();
        AewmeService.weixinActionTime = System.currentTimeMillis();
        AppUtils.startApp(this, WeChatTextWrapper.WECAHT_PACKAGENAME, WeChatTextWrapper.WechatClass.WECHAT_CLASS_LAUNCHUI);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                AppUtils.startApp(FeiLongService.this, WeChatTextWrapper.WECAHT_PACKAGENAME, WeChatTextWrapper.WechatClass.WECHAT_CLASS_MAINSEARCH);
            }
        }, 1000);

    }

    /**
     * 收到启动微信的指令
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(WechatHomeFinish event) throws RemoteException {
        startWechat();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(GlobalEvent event) throws RemoteException {
        Log.d(TAG, "helper GlobalEvent : " + event.toString());
        if (event.getType() == 1) {
//            ttsHelpers.pause();
            ttsHelpers.setInterrupted(true);
            ttsHelpers.endTTS();
        } else if (event.getType() == 2) {
            ttsHelpers.resume();
        }
    }

    private String wxTips = "请说要发的内容";

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CurrentUI current) throws RemoteException {
        if (feilongRespone != null && AewmeService.currentActivity.equals(WeChatTextWrapper.WechatClass.WECHAT_CLASS_CHATUI) && feilongRespone.getIntent().equals("sendweixin") && feilongRespone != null) {
            currentTTS = "";
            ttsHelpers.startTTS(wxTips, TTSHelper.AWAKE_TYPE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AskFeilong askFeilong) throws RemoteException {
        sendToFeiLongByUI(askFeilong.getAsk());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(PlayTTs event) throws RemoteException {
        ttsHelpers.startTTS(event.getText(), TEXT_TYPE);

        if (getString(R.string.update_xxz_success).equals(event.getText())) {
            sendToFeiLongByIntent("exit");

        } else if (getString(R.string.start_update_xxz).equals(event.getText())) {
            handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
        }
    }


    private String userPhone;
    private StringBuilder iatRes = new StringBuilder();

    private boolean enType;

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startForeground() {
        // Create Notification Channel
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "feilong",
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }

        // Create Notification
        Notification notification = new Notification.Builder(this, CHANNEL_ID)
                .setContentTitle("Foreground Service")
                .setContentText("Service is running...")
                .setPriority(Notification.PRIORITY_LOW)
                .build();

        // Start Foreground Service with notification
        startForeground(NOTIFICATION_ID, notification);
    }


    private String address = "";


    private void getAdress(String result) {
        try {
            LocationBase base = new Gson().fromJson(result, LocationBase.class);
            address = base.getResult().getFormattedAddress();
//            Log.d(TAG, "onSuccess getLocation..>>" + result);
            Log.d(TAG, "onSuccess adress..>>" + address);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(callEndReceiver);
            unregisterReceiver(bootBroadcast);
            unregisterReceiver(bleStateReceiver);
            unregisterReceiver(langChangeReceiver);
            connectivityManager.unregisterNetworkCallback(networkCallback);
//        if (null != ttsHelper) {
//            ttsHelper.destroy();
//        }
            if (null != playerUtils) {
                playerUtils.release();
            }
            if (EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().unregister(this);
            }
            alertVoiceManager.release();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onVoiceBtnClick() {
        if (null != ttsHelpers) {
            ttsHelpers.setInterrupted(true);
            ttsHelpers.endTTS();
        }
        recognitionModel();
        if (ivwHelper != null) {
            startSpeechRecognition();
        }
        musicPlayer.stop();
    }


    @Override
    public void onDimiss() {
        Log.d(TAG, "onDimiss: stopSpeechRecognition");
        if (null != cancelable) {
            cancelable.cancel();
        }
        stopSpeechRecognition();
        if (null != ttsHelpers) {
            ttsHelpers.setInterrupted(true);
            ttsHelpers.endTTS();
        }
        musicPlayer.stop();
    }

    @Override
    public void onPlayEnd() {
        Log.d(TAG, "onCompletion: ");
        ttsFinish(TTSHelper.TEXT_TYPE);

    }

    @Override
    public void onTextChanged(String text) {
        recognitionResult(text);
    }

    @Override
    public void onShowEdit() {//编辑问题时对话框不消失
        handler.removeMessages(CLOSE_VOICE_LAYOUT);
    }

    private void permissionsBlueToochInit(boolean needOpen) {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
        };
        if (!EasyPermissions.hasPermissions(this, perms)) {
            // 没有权限，进行权限请求
            return;
        }
        //安卓12或以上，还需要蓝牙连接附近设备的权限
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            perms = new String[]{
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.BLUETOOTH_ADVERTISE,
                    Manifest.permission.BLUETOOTH_CONNECT
            };
            if (!EasyPermissions.hasPermissions(this, perms)) {
                // 没有蓝牙权限，进行权限请求
                return;
            }
            //权限获取成功，可以使用蓝牙
        } else {
            //权限获取成功，可以使用蓝牙
        }
        initBlueTooch(needOpen);
    }

    private void initBlueTooch(boolean needOpen) {
        Log.d(TAG, "initBlueTooch: needOpen=" + needOpen);
        if (needOpen) {
            EdgeManager.getInstance().openBluetooth();
        }
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
                if (blueAdapter != null && blueAdapter.isEnabled()) {
                    Log.d(TAG, "initBlueTooch: ");
                    connectDevice();
                } else {

                }
            }
        }, 400);

    }

    private boolean called;
    PhoneStateListener phoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            Log.d(TAG, "onCallStateChanged: " + state);
            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    String[] perms = {Manifest.permission.RECORD_AUDIO
                    };
                    Log.d(TAG, "onCallStateChanged: 权限=" + EasyPermissions.hasPermissions(FeiLongService.this, perms));
                    if (!EasyPermissions.hasPermissions(FeiLongService.this, perms)) {
                        Log.e(TAG, "onCallStateChanged: 没有权限，进行权限请求");
                        // 没有权限，进行权限请求
//                        EasyPermissions.requestPermissions(this,"请打开应用的定位权限",0, perms);
                        return;
                    }
                    if (called) {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ivwHelper.startIvw();
                                ivwHelper.resumeRecord();
                            }
                        }, 2000);
                        Log.d(TAG, "onCallStateChanged:  ivwHelper.startIvw()" + state);
                        called = false;
                    }
                    // 空闲状态，没有任何活动
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    // 响铃状态，有电话呼入
//                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    called = true;
                    ivwHelper.stopIvw();
                    tag = "onCallStateChanged";
                    Log.d(TAG, "@@@onCallStateChanged:  ivwHelper.stopIvw()" + state);
                    handler.sendEmptyMessage(CLOSE_VOICE_LAYOUT);
                    // 摘机状态，正在通话中
                    break;
            }
        }

        @Override
        public void onDataConnectionStateChanged(int state) {
            Log.d(TAG, "onDataConnectionStateChanged: " + state);
            switch (state) {
                case TelephonyManager.DATA_DISCONNECTED:
                    // 断开连接
                    break;
                case TelephonyManager.DATA_CONNECTING:
                    // 连接中
                    break;
                case TelephonyManager.DATA_CONNECTED:
                    // 已连接
                    break;
            }
        }
    };

    class BLEStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(final Context context, Intent intent) {
            checkBLEState(context, intent);
            Log.d(TAG, "onReceive: unSendAllGoData=" + unSendAllGoData);
        }

        /**
         * 检测蓝牙状态
         *
         * @param context
         * @param intent
         */
        private synchronized void checkBLEState(Context context, Intent intent) {
            int BLEState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
            switch (BLEState) {
                case BluetoothAdapter.STATE_ON:
                    Log.d(TAG, "checkBLEState: STATE_ON");
                    connectDevice();
                    // 蓝牙已经打开
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.d(TAG, "checkBLEState: STATE_TURNING_OFF");
                    // 蓝牙正在关闭
                    break;
            }
        }

    }

    private double latitude, longitude;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();

    class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null == location) {
                return;
            }
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            List<Poi> pois = location.getPoiList();
            if (null == pois) {
                return;
            }
            if (!pois.isEmpty()) {
                address = pois.get(0).getAddr();
            } else {
                address = location.getAddress().address;    //获取城市
            }
            if (!TextUtils.isEmpty(address)) {
                SPUtils.getInstance().put("address", address);
            }
            Log.d(TAG, "onReceiveLocation: " + address);
        }
    }

    public void getLocation() {

        try {
            mLocationClient = new LocationClient(this);
            Log.e(TAG, "onCreate: " + mLocationClient);
            mLocationClient.registerLocationListener(myListener);
            LocationClientOption option = new LocationClientOption();
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置高精度定位
            option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
            option.setScanSpan(0);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
            option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
            option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
            option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
            option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
            option.SetIgnoreCacheException(false);
            mLocationClient.setLocOption(option);
            mLocationClient.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void requestLocation() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
        };
        if (!EasyPermissions.hasPermissions(this, perms)) {
            return;
        }
        getLocation();
    }

    private ConnectivityManager connectivityManager;
    private NetworkRequest networkRequest;
    private ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            Log.d(TAG, "onAvailable: 网络变得可用");
            // 网络变得可用时的操作
            if (AbilityInit.IFLYTECK_FAIL_BY_NO_NETWORK) {
                handler.removeMessages(RESTART_VOICE);
                handler.sendEmptyMessageDelayed(RESTART_VOICE, 1000);
            }
        }

        @Override
        public void onLost(Network network) {
            Log.d(TAG, "onLost: 网络断开");
            // 网络断开时的操作
        }

        // 其他需要重写的方法...
    };

    /**
     * 监听网络状态
     */
    private void registeNetWork() {
        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        networkRequest = new NetworkRequest.Builder()
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .build();

        connectivityManager.registerNetworkCallback(networkRequest, networkCallback);
    }

    /**
     *
     */
    private void checkScreen() {
        if (!AppUtils.checkScreenOn(FeiLongService.this)) {
            AppUtils.execKeyevent("224");//亮屏
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Log.e(TAG, "onWakeup: " + AewmeService.currentPackageName);
                    if ("com.android.systemui".equals(AewmeService.anyPackageName)) {
                        AppUtils.execCommand("adb shell input swipe 300 1000 300 500");//上划解锁
                    }
                }
            }, 1000);
        }
    }

    /**
     * 这些方法是rom方通过广播调用
     *
     * @param action
     */
    private void invokeSystemSetting(String action) {
        sendBroadcast(new Intent(action));
        ttsHelpers.startTTS("好的", ttsType);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TakeVideo takeVideo) throws RemoteException {
        takeVideo(takeVideo);
    }

    private MediaRecorder mMediaRecorder;
    private MediaProjection mediaProjection;

    /**
     * 录屏功能
     *
     * @param takeVideo
     */
    private void takeVideo(TakeVideo takeVideo) {
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        MediaProjection mediaProjection = mediaProjectionManager.getMediaProjection(takeVideo.getResultCode(), takeVideo.getIntent());
        // 用户同意了屏幕捕获，创建MediaProjection对象
        DisplayMetrics displayMetrics = new DisplayMetrics();

// 获取窗口管理器
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

// 通过窗口管理器获取默认显示的信息，并将其填充到DisplayMetrics对象中
        if (windowManager != null) {
            Display defaultDisplay = windowManager.getDefaultDisplay();
            defaultDisplay.getMetrics(displayMetrics);
        }

// 获取当前屏幕的密度（dpi）
        int densityDpi = displayMetrics.densityDpi;
        // 创建虚拟Display和MediaRecorder来录制屏幕
        VirtualDisplay virtualDisplay = mediaProjection.createVirtualDisplay(
                "ScreenRecording",
                displayMetrics.widthPixels, displayMetrics.heightPixels,
                displayMetrics.densityDpi,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mMediaRecorder.getSurface(),
                null /*Callbacks*/, null /*Handler*/);

        // 设置MediaRecorder并开始录制
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setOutputFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/screen_recording.mp4");
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        // 设置其他视频参数...
        try {
            mMediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mMediaRecorder.start();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                stopRecording();
            }
        }, 5000);
        // 录制完成后停止MediaRecorder和释放资源
        // ...
    }


    // 不要忘记在结束时清理资源
    public void stopRecording() {
        if (mMediaRecorder != null) {
            mMediaRecorder.stop();
            mMediaRecorder.release();
        }

        if (mediaProjection != null) {
            mediaProjection.stop();
        }
    }

    /**
     * 跳转到提醒/记忆/理解的通讯录
     */
    private void goRemindList() {
        ARouter.getInstance().build(Constant.ACTIVITY_URL_REMIND)
                .withSerializable("feilongRespone", feilongRespone)
                .navigation();
    }

    private static final int maxTTsLen = 1000;//tts最多支持的字数
    private Callback.Cancelable cancelable;
    private AIRespone aiRespone;

    private void getTalk(String key, String userid) {
        RequestParams params = new RequestParams(Constant.TALK_URL + "pp/talk");
        params.addParameter("action", "talk_feilong");
        params.addParameter("key", key);
        params.addParameter("userid", userid);

        boolean isNetworkAvailable = NetworkUtil.isNetworkAvailable(FeiLongService.this);
        if (TextUtils.isEmpty(feilongRespone.getText())) {
            if (isNetworkAvailable) {
                String[] arr = getResources().getStringArray(R.array.ask_loading_tips);
                Random random = new Random();
                int index = random.nextInt(arr.length);
                String tip = arr[index];
                floatingView.setAnswerViewText(tip);
                if (tip.contains("……")) {
                    tip = tip.substring(0, tip.indexOf("……"));
                }
                ttsHelpers.startTTS(tip, TIPS_TYPE);
            } else {
                floatingView.setAnswerViewText(getString(R.string.network_error));
            }
        } else {
            floatingView.setAnswerViewText(feilongRespone.getText());
            ttsHelpers.startTTS(feilongRespone.getText(), TIPS_TYPE);
        }

        Log.d(TAG, "checkForUpdates: " + params.toString());
        cancelable = org.xutils.x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: +" + result);
//                String keyWord = key.replace("[xfapi]", "");
//                if (null != askContent && !keyWord.equals(askContent)) {
//                    return;
//                }

                Gson gson = new Gson();
                BaseResult baseCode = gson.fromJson(result, BaseResult.class);
                aiRespone = gson.fromJson(baseCode.getData(), AIRespone.class);
                FeilongRespone feilongRespone = gson.fromJson(result, FeilongRespone.class);
                feilongRespone.setIntent("apirecev");
//                sendToTcp(feilongRespone);
                Log.d(TAG, "onSuccess:ttsHelpers.isPlaying()= " + ttsHelpers.isPlaying());
                if (!ttsHelpers.isPlaying()) {
                    showOnlieResult();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                aiRespone = null;
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                aiRespone = null;
                cex.printStackTrace();
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void getNetTalk(String flow, String text, String mode) {
        RequestParams params = new RequestParams(Constant.TALK_NET_URL + "get_list");
        params.addParameter("text", text);
        params.addParameter("session", Session);
        params.addParameter("imei", "android_test");
        params.addParameter("flow", flow);
        params.addParameter("mode", mode);

        boolean isNetworkAvailable = NetworkUtil.isNetworkAvailable(FeiLongService.this);

        cancelable = org.xutils.x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.d(TAG, "onSuccess: +" + result);

                Gson gson = new Gson();
                AINetRespone aINetRespone = gson.fromJson(result, AINetRespone.class);
                String resultVoice = "";
                if (Flow.equals("0")) {
                    resultVoice = "好的，已进入购物模式" + aINetRespone.text;
                } else {
                    resultVoice = aINetRespone.text;
                }
                if (aINetRespone != null && aINetRespone.data != null && aINetRespone.data.size() > 0) {
                    if (aINetRespone.type.equals("images")) {
                        floatingView.setVoiceData(aINetRespone.data);
                    }
                    if (aINetRespone.type.equals("url")) {
                        floatingView.cleanVoiceData();
                        feilongRespone.setUrl(aINetRespone.data.get(0).url);
                        feilongRespone.setText("支付页面");
                        ARouter.getInstance().build(Constant.ACTIVITY_URL_WEB)
                                .withSerializable("feilongRespone", feilongRespone)
                                .navigation();
                    }
                }

                if (aINetRespone != null && aINetRespone.finish.equals("1")) {
                    Flow = "0";
                } else {
                    Flow = aINetRespone.flow;
                }

                ttsHelpers.startTTS(resultVoice, TTSHelper.TEXT_TYPE);
                String finalResultVoice = resultVoice;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        floatingView.setAnswerViewText(finalResultVoice);
                    }
                });
//                handler.sendEmptyMessage(AWAKEMODEL);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
//                aiRespone = null;
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {
//                aiRespone = null;
                cex.printStackTrace();
            }

            @Override
            public void onFinished() {
            }
        });
    }


    private void addWarn(String result) {
        String temp = ChineseNumberConverter.convertChineseToArabic(result);
        if (result.contains("小时")) {
            setDayclock(result, System.currentTimeMillis() + Long.valueOf(geth(temp)) * 3600 * 1000);
        } else if (result.contains("分钟")) {
            setDayclock(result, System.currentTimeMillis() + Long.valueOf(getmi(temp)) * 60 * 1000);
        } else if (result.contains("秒")) {
            setDayclock(result, System.currentTimeMillis() + Long.valueOf(gets(temp)) * 1000);
        } else if (result.contains("刻钟")) {
            setDayclock(result, System.currentTimeMillis() + Long.valueOf(getke(temp)) * 15 * 60 * 1000);
        } else {
            FixTime(result);
        }


//        AddWarnMsg
    }

    private void queryWarn() {
//        QueryWarnMsg
    }

    private void deleteWarn() {
//        DeleteWarnMsg
    }

    private void showOnlieResult() {
        if (null == aiRespone) return;
        String result = aiRespone.getData().replaceAll("\\\n\\\n", "");
        String tts = result;
        if (!result.isEmpty() && result.length() > maxTTsLen) {
            tts = result.substring(0, maxTTsLen);
        }
        Log.d(TAG, "showOnlieResult: " + tts);
//        ttsHelpers.stop();
        ttsHelpers.startTTS(tts, TEXT_TYPE);
        handler.post(new Runnable() {
            @Override
            public void run() {
                awakeModel();
                floatingView.setAnswerViewText(result);
            }
        });
        handler.removeMessages(CLOSE_VOICE_LAYOUT);
        aiRespone = null;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AIUIMsg aiuiMsg) throws RemoteException {
        if (aiuiMsg.getAIUIMsg().equals("0")) {
            commonOnWakeup(TTSHelper.AIAUI_TYPE);
            awakeModel();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    floatingView.recognitionModel();
                }
            }, 3000);
//            floatingView.recognitionModel();
//            StartOnce();
//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    floatingView.recognitionModel();
//                }
//            }, 3000);
        } else {
            showAIUIResult(aiuiMsg.getAIUIMsg(), aiuiMsg.type);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(StarOnLineMsg aiuiMsg) throws RemoteException {
        if (aiuiMsg.aiuiMsg.equals("0")) {
            commonOnWakeup(TTSHelper.AWAKE_TYPE);
        } else {
            commonOnFirstWakeup(TTSHelper.AWAKE_TYPE);
        }
        awakeModel();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(AIUICleanMsg aiuiMsg) throws RemoteException {
        if (null != floatingView) {
            floatingView.setAskViewText("");
            floatingView.hide();
//                        handler.sendEmptyMessageDelayed(TCP_CHECK, 15000);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(StartAskMsg aiuiMsg) throws RemoteException {
        floatingView.setAskViewText(aiuiMsg.getAIUIMsg());
    }


    private void showAIUIResult(String text, int msgType) {
        String result = text;
        String tts = "";
        if (msgType == 6) {
            tts = "主人你的问题正在计算";
        } else {
            tts = result;
        }
        if (!result.isEmpty() && result.length() > maxTTsLen) {
            tts = result.substring(0, maxTTsLen);
        }
        Log.d(TAG, "showOnlieResult: " + tts);
//        ttsHelpers.stop();
        ttsHelpers.startTTS(tts, TEXT_TYPE);
        handler.post(new Runnable() {
            @Override
            public void run() {
                awakeModel();
                floatingView.setAnswerViewText(result);
            }
        });
        handler.removeMessages(CLOSE_VOICE_LAYOUT);
        EventBus.getDefault().post(new StartAIUI());
    }


    public static String unicodeToString(String unicode) {
        StringBuilder sb = new StringBuilder();
        String[] hex = unicode.split("\\\\u");

        for (int i = 1; i < hex.length; i++) {
            int value = Integer.parseInt(hex[i], 16);
            sb.append((char) value);
        }

        return sb.toString();
    }

    public void startOnce() {
        if (null != ttsHelpers) {
            ttsHelpers.setInterrupted(true);
            ttsHelpers.endTTS();
        }
        recognitionModel();
        if (ivwHelper != null) {
            startSpeechRecognition();
        }
        musicPlayer.stop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(StartOnceMsg command) throws RemoteException {
        startOnce();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ToggleMsg command) throws RemoteException {
        isToggle = false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ToastMsg command) throws RemoteException {
        if (floatingView != null && floatingView.isShowing()) {
            floatingView.showToast();
        }
    }

//    public int chineseToArabic(String chineseNumber) {
//        String[] chineseNums = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
//        char[] chineseNumChars = chineseNumber.toCharArray();
//        int result = 0;
//        int temp = 1;
//        int count = 0;
//
//        for (int i = 0; i < chineseNumChars.length; i++) {
//            boolean isUnit = false;
//            for (String chineseNum : chineseNums) {
//                if (chineseNum.charAt(0) == chineseNumChars[i]) {
//                    if (chineseNum.equals("零")) {
//                        temp = 0;
//                    } else {
//                        temp = Integer.parseInt(chineseNum.substring(0, 1));
//                    }
//
//                    if (i + 1 < chineseNumChars.length && chineseNumChars[i + 1] == '十') {
//                        temp *= 10;
//                        i++; // 跳过 '十' 字
//                        isUnit = true;
//                    } else if (i + 2 < chineseNumChars.length && chineseNumChars[i + 1] == '百' && chineseNumChars[i + 2] == '千') {
//                        temp *= 1000;
//                        i += 2; // 跳过 '百' 和 '千'
//                        isUnit = true;
//                    }
//
//                    if (isUnit) {
//                        result += temp;
//                        temp = 1;
//                    } else {
//                        result += temp * Math.pow(10, count);
//                        count++;
//                    }
//                    break;
//                }
//            }
//        }
//
//        return result;
//    }

    public String getNum(String num, String result) {
        String temp = "";
        String regex = "(?<=.)" + num;
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        while (matcher.find()) {
            if (matcher.start() > 0) {
                temp = String.valueOf(result.charAt(matcher.start() - 1));
            }
        }
        return temp;
    }

    public String getPoint(String result) {
        String temp = "";
        String regex = "(\\d+)点";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        if (matcher.find()) {
            temp = matcher.group(1);
        }
        return temp;
    }

    public String getm(String result) {
        String temp = "";
        String regex = "(\\d+)月";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        if (matcher.find()) {
            temp = matcher.group(1);
        }
        return temp;
    }

    public String getd(String result) {
        String temp = "";
        String regex = "(\\d+)号";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        if (matcher.find()) {
            temp = matcher.group(1);
        }
        return temp;
    }

    public String getdd(String result) {
        String temp = "";
        String regex = "(\\d+)日";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        if (matcher.find()) {
            temp = matcher.group(1);
        }
        return temp;
    }

    public String geth(String result) {
        String temp = "";
        String regex = "(\\d+)小时";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        if (matcher.find()) {
            temp = matcher.group(1);
        }
        return temp;
    }

    public String getmi(String result) {
        String temp = "";
        String regex = "(\\d+)分钟";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        if (matcher.find()) {
            temp = matcher.group(1);
        }
        return temp;
    }

    public String gets(String result) {
        String temp = "";
        String regex = "(\\d+)秒";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        if (matcher.find()) {
            temp = matcher.group(1);
        }
        return temp;
    }

    public String getke(String result) {
        String temp = "";
        String regex = "(\\d+)刻钟";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        if (matcher.find()) {
            temp = matcher.group(1);
        }
        return temp;
    }

    public String getTime(String result) {
        String temp = "";
        String regex = "([01]?[0-9]|2[0-3]):[0-5][0-9](?::[0-5][0-9])?";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(result);

        while (matcher.find()) {
            temp = matcher.group();
        }
        return temp;
    }

    public String getHour(String result) {
        int indexOfPoint = result.indexOf("点");
        if (indexOfPoint != -1 && indexOfPoint > 0) {
            // 确保“点”前面有字符，并且这些字符是数字
            String beforePoint = result.substring(0, indexOfPoint);
            if (beforePoint.matches("\\d{1,2}")) {
                return beforePoint;
            }
        }
        return null;
    }


    public void FixTime(String result) {
        String y = yearsScreen(result);
        String m = monthScreen(result);
        String d = dayScreen(result);
        String time = getTime(result);
        if (time != null && time.length() > 0) {
            if (time.length() != 8) {
                time = time + ":00";
            }
        } else {
            String hour = getHour(result);
            if (hour != null && hour.length() > 0) {
                time = hour + ":00:00";
            } else {
                String point = getPoint(result);
                if (point != null && point.length() > 0) {
                    if (point.length() < 2) {
                        time = "0" + point + ":00:00";
                    } else {
                        time = point + ":00:00";
                    }
                } else {
                    time = "00:00:00";
                }
            }
        }

        if (result.contains("下午") || result.contains("晚上") || result.contains("夜里")|| result.contains("傍晚")) {
            String temph = time.substring(0, 2);
            temph = String.valueOf(Integer.valueOf(temph) + 12);
            String newString = time.substring(2);
            time = temph + newString;
        }
        String times = y + "-" + m + "-" + d + " " + time;
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8");
        long timestamp = getTimestampOfDayStart(times, timeZone);


        setclock(result, timestamp, y, m, d, time, times);
//        int temp=chineseToArabic.get(result);
    }

    private void setclock(String result, long timestamp, String y, String m, String d, String time, String times) {
        AlarmClockHelper.setCirculateAlarmClock(this, timestamp, "0");
        List<RemindBean> remindBeans = new ArrayList<>();
        RemindBean remindBean = new RemindBean(
                0, "a", "0", "a", "a", "a",
                "a", y + "-" + m + "-" + d, time, timestamp, "a", time,
                "a", extractTextAfterKeyword(result, "提醒我"), "a", "a", "a",
                "a"
        );
        remindBeans.add(remindBean);
        RemindDatabase.getDefault(getApplicationContext()).getRemindDao().insertAll(remindBeans);
        EventBus.getDefault().post(new AIUIMsg("好的，" + times + "提醒您" + extractTextAfterKeyword(result, "提醒我")));
        Log.d("aaaaaaaaaaaaaaa", "时间:" + times + "---" + "时间戳:" + timestamp + "---" + "内容:" + result);
    }

    private void setDayclock(String result, long timestamp) {
        String times = timestampToDateTime(timestamp);
        String[] parts = times.split(" ");
        String datePart = parts[0];
        String timePart = parts[1];
        AlarmClockHelper.setCirculateAlarmClock(this, timestamp, "0");
        List<RemindBean> remindBeans = new ArrayList<>();
        RemindBean remindBean = new RemindBean(
                0, "a", "0", "a", "a", "a",
                "a", datePart, timePart, timestamp, "a", timePart,
                "a", extractTextAfterKeyword(result, "提醒我"), "a", "a", "a",
                "a"
        );
        remindBeans.add(remindBean);
        RemindDatabase.getDefault(getApplicationContext()).getRemindDao().insertAll(remindBeans);
        EventBus.getDefault().post(new AIUIMsg("好的，" + times + "提醒您" + extractTextAfterKeyword(result, "提醒我")));
        Log.d("aaaaaaaaaaaaaaa", "时间:" + times + "---" + "时间戳:" + timestamp + "---" + "内容:" + result);
    }

    public String yearsScreen(String result) {
        String y = "";
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        y = String.valueOf(year);
        if (result.contains("今年")) {
            y = String.valueOf(year);
        } else if (result.contains("明年")) {
            y = String.valueOf(year + 1);
        } else if (result.contains("后年")) {
            y = String.valueOf(year + 2);
        }
        return y;
    }

    public String monthScreen(String result) {
        String m = "";
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH);
        m = String.valueOf(month + 1);
        if (result.contains("这月")) {
            m = String.valueOf(m);
        } else if (result.contains("这个月")) {
            m = String.valueOf(m);
        } else if (result.contains("下月")) {
            m = String.valueOf(month + 2);
        } else if (result.contains("下个月")) {
            m = String.valueOf(month + 2);
        } else if (result.contains("月")) {
            m = getm(result);
        }
        if (m.length() < 2) {
            m = "0" + m;
        }
        return m;
    }

    public String dayScreen(String result) {
        String d = "";
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        d = String.valueOf(day);
        if (result.contains("今天")) {
            d = String.valueOf(day);
        } else if (result.contains("明天")) {
            d = String.valueOf(day + 1);
        } else if (result.contains("大后天")) {
            d = String.valueOf(day + 3);
        } else if (result.contains("后天")) {
            d = String.valueOf(day + 2);
        } else if (result.contains("号")) {
            d = getd(result);
        }else if (result.contains("日")) {
            d = getdd(result);
        }
        if (d.length() < 2) {
            d = "0" + d;
        }
        return d;
    }


    public void weeksScreen(String result) {
        if (result.contains("这周")) {

        } else if (result.contains("下周")) {

        } else if (result.contains("下下周")) {

        }
    }

    public static long getTimestampOfDayStart(String dateString, TimeZone timeZone) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(timeZone);
        try {
            Date date = sdf.parse(dateString);
            Calendar calendar = Calendar.getInstance(timeZone);
            calendar.setTime(date);
            return calendar.getTimeInMillis();
        } catch (ParseException e) {
            e.printStackTrace();
            return -1;
        }
    }

//    private static final Map<String, Integer> chineseToArabic = new HashMap<>();
//
//    static {
//        chineseToArabic.put("一", 1);
//        chineseToArabic.put("二", 2);
//        chineseToArabic.put("三", 3);
//        chineseToArabic.put("四", 4);
//        chineseToArabic.put("五", 5);
//        chineseToArabic.put("六", 6);
//        chineseToArabic.put("七", 7);
//        chineseToArabic.put("八", 8);
//        chineseToArabic.put("九", 9);
//        chineseToArabic.put("十", 10);
//        for (int i = 1; i <= 9; i++) {
//            String prefix = "十" + chineseToArabic.get(String.valueOf(i));
//            chineseToArabic.put(prefix, 10 + i);
//        }
//        for (int i = 2; i <= 6; i++) {
//            String prefix = i + "十";
//            chineseToArabic.put(prefix, i * 10);
//            for (int j = 1; j <= 9; j++) {
//                String fullNumber = prefix + chineseToArabic.get(String.valueOf(j));
//                chineseToArabic.put(fullNumber, i * 10 + j);
//            }
//        }
//    }

    public String extractTextAfterKeyword(String input, String keyword) {
        int index = input.indexOf(keyword);
        if (index != -1) {
            return input.substring(index + keyword.length());
        }
        return "";
    }

    public static String timestampToDateTime(long timestamp) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        Date date = new Date(timestamp);
        return simpleDateFormat.format(date);
    }


}